package day27;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

//模拟多人聊天室
public class Server3 {
    //用于保存进入聊天室的客户端对象
    static List<Socket> list=new ArrayList<>();

    public static void main(String[] args) throws IOException {
        ServerSocket server=new ServerSocket(9999);
        System.out.println("***多人聊天室开启成功***");
        while (true){
            Socket client=server.accept();
            list.add(client); //添加群聊
            System.out.println("聊天室:"+list.size()+"人");
            //创建线程负责每个客户端的读写
            new Server3Thread(client).start();
        }
    }
}
class Server3Thread extends Thread{
    Socket client;
    public Server3Thread(Socket client){
        this.client=client;
    }
    //负责当前客户端数据读取，将读取数据转发给其他客户端（除了自己）
    public void run() {
        try {
            BufferedReader br=new BufferedReader(new InputStreamReader(client.getInputStream()));
            while (true){
                String msg= br.readLine();
                System.out.println(msg);
                //退出聊天室  退出
                if(msg.contains("退出")){
                    Server3.list.remove(client);
                    System.out.println("聊天室"+Server3.list.size()+"人");
                    return; //结束当前方法 结束线程
                }
                //向其他客户端写入(发送)
                for (Socket s:Server3.list){
                    //排除自己(client)，向其他人法
                    if (s!=client){
                        OutputStream os= s.getOutputStream();
                        os.write((msg+"\n").getBytes());
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
